package class10;

import java.util.HashMap;
import java.util.Map;

/**
 * 设计有 setall功能的哈希表
 * 原始：map(3, 27),(5,13),(17,5)...
 * 变成：map(3, 100),(5,100),(17,100)...
 * 解题思路:
 * 1.map的val用长度为2的数组存放，int[0]存传入的value,int[1]存时间戳
 * 2.当调用setAll方法时，更新setAllTime,和setAllVal
 */
public class Code08_setAll {
    public static void main(String[] args) {
        HashMapSetAll hashMapSetAll = new HashMapSetAll();
        hashMapSetAll.put(3, 27);
        hashMapSetAll.put(4, 32);
        hashMapSetAll.setAll(100);
        System.out.println(hashMapSetAll.get(3));
        System.out.println(hashMapSetAll.get(4));
        hashMapSetAll.put(5, 69);
        System.out.println(hashMapSetAll.get(5));
    }

    private static class HashMapSetAll {
        private int times = 0;
        private int setAllTime = -1;
        private int setAllVal = 0;

        Map<Integer, int[]> map;

        public HashMapSetAll() {
            map = new HashMap<>();
        }

        public void put(int k, int v) {
            map.put(k, new int[]{v, times++});
        }

        public Integer get(int k) {
            if (map.containsKey(k)) {
                int[] res = map.get(k);
                // 判断当前值的时间戳是否晚于setAll的时间
                return res[1] < setAllTime ? setAllVal : res[0];
            }
            return null;

        }

        public void setAll(int val) {
            setAllTime = times;
            setAllVal = val;
        }
    }
}
